package com.xinrui.sunnyday.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xinrui.sunnyday.constant.MessageConstant;
import com.xinrui.sunnyday.entity.Result;
import com.xinrui.sunnyday.service.MemberService;
import com.xinrui.sunnyday.service.ReportService;
import com.xinrui.sunnyday.service.SetmealService;
import com.xinrui.sunnyday.utils.DateUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.*;

@RestController
@RequestMapping("/report")
public class ReportController {
    @Reference
    private MemberService memberService;

    @Reference
    private SetmealService setmealService;

    @Reference
    private ReportService reportService;

    /**
     * 会员折线图
     * @return
     */
    @GetMapping("/getMemberReport")
    public Result getMemberReport(){
        //组装过去12个月的数据
        List<String> months = new ArrayList<>();
        //使用calendar来操作日期
        Calendar calendar = Calendar.getInstance();
        //设置过去一年的时间  获取当前年 -1
        calendar.add(Calendar.YEAR,-1);
        //构建12个月的数据 从第一个月开始加 for循环操作
        for (int i = 0;i < 12;i++){
            try {
                //每次增加一个月
                calendar.add(Calendar.MONTH,1);
                //过去的日期
                Date date = calendar.getTime();
                //转换时间为字符串
                String dateString = DateUtils.parseDate2String(date);
                //添加拼好的12个月到List集合
                months.add(dateString);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //查询数据库过去12个月的数据 添加进集合
        List<Integer> memberCount = memberService.getMemberReport(months);
        //放入map
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("months",months);
        resultMap.put("memberCount",memberCount);
        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,resultMap);
    }

    /**
     * 套餐扇形图
     * @return
     */
    @GetMapping("/getSetmealReport")
    public Result getSetmealReport(){
        //调用方法查询套餐预约占比
        List<Map<String,Object>> setmealCount = setmealService.findSetmealCount();
        Map<String,Object> map = new HashMap<>();
        map.put("setmealCount",setmealCount);
        //抽取套餐名称集合
        List<String> setmealNames = new ArrayList<>();
        for (Map<String, Object> objectMap : setmealCount) {
            //获取名称
            String name = (String) objectMap.get("name");
            //添加入集合
            setmealNames.add(name);
        }
        //回显
        map.put("setmealNames",setmealNames);
        return new Result(true,MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,map);
    }

    /**
     * 获取运营统计数量
     * @return
     */
    @GetMapping("/getBusinessReportData")
    public Result getBusinessReportData() throws Exception {
        Map<String,Object> reportMap = reportService.getBusinessReportData();
        return new Result(true,MessageConstant.GET_BUSINESS_REPORT_SUCCESS,reportMap);
    }

    @GetMapping("/exportBusinessReport")
    public void exportBusinessReport(HttpServletRequest req, HttpServletResponse res) throws Exception {
        //获取运营数据
        Map<String,Object> reportData = reportService.getBusinessReportData();
        //获取模板的路径
        String template = req.getSession().getServletContext().getRealPath("/template/report_template.xlsx");
        //创建工作簿
        try (FileInputStream fis = new FileInputStream(template);
             OutputStream os = res.getOutputStream();
             Workbook workbook = new XSSFWorkbook(fis)
        ) {
            //获取工作表
            XSSFSheet sheet = (XSSFSheet) workbook.getSheetAt(0);
            //设置日期坐标
            sheet.getRow(2).getCell(5).setCellValue(reportData.get("reportDate").toString());
            //设置今日新增会员坐标
            sheet.getRow(4).getCell(5).setCellValue((Integer)reportData.get("todayNewMember"));
            //设置总会员坐标
            sheet.getRow(4).getCell(7).setCellValue((Integer)reportData.get("totalMember"));
            //设置本周新增会员坐标
            sheet.getRow(5).getCell(5).setCellValue((Integer)reportData.get("thisWeekNewMember"));
            //设置本月新增会员坐标
            sheet.getRow(5).getCell(7).setCellValue((Integer)reportData.get("thisMonthNewMember"));
            //设置今日预约数
            sheet.getRow(7).getCell(5).setCellValue((Integer)reportData.get("todayOrderNumber"));
            //设置今日到诊数
            sheet.getRow(7).getCell(7).setCellValue((Integer)reportData.get("todayVisitsNumber"));
            //设置本周预约数
            sheet.getRow(8).getCell(5).setCellValue((Integer)reportData.get("thisWeekOrderNumber"));
            //设置本周到诊数
            sheet.getRow(8).getCell(7).setCellValue((Integer)reportData.get("thisWeekVisitsNumber"));
            //设置本月预约数
            sheet.getRow(9).getCell(5).setCellValue((Integer)reportData.get("thisMonthOrderNumber"));
            //设置本月到诊数
            sheet.getRow(9).getCell(7).setCellValue((Integer)reportData.get("thisMonthVisitsNumber"));

            //获取热门套餐集合
            List<Map<String,Object>> hotSetmeal = (List<Map<String, Object>>) reportData.get("hotSetmeal");
            //获取行
            int row = 12;
            //遍历集合获取数据
            for (Map<String, Object> setmealMap : hotSetmeal) {
                //套餐名称
                sheet.getRow(row).getCell(4).setCellValue((String) setmealMap.get("name"));
                //预约数量
                sheet.getRow(row).getCell(5).setCellValue((Long)setmealMap.get("setmeal_count"));
                BigDecimal decimal = (BigDecimal) setmealMap.get("proportion");
                //占比
                sheet.getRow(row).getCell(6).setCellValue(decimal.doubleValue());
                //备注
                sheet.getRow(row).getCell(7).setCellValue((String) setmealMap.get("remark"));
                //循环一行
                row++;
            }
            //设置文件名称
            String fileName = "运营统计数据报表.xlsx";
            //解决中文乱码
            fileName = new String(fileName.getBytes(StandardCharsets.UTF_8),"ISO-8859-1");
            // 设置头信息，告诉浏览器，是带附件的，文件下载
            res.setHeader("Content-Disposition","attachement;filename=" + fileName);
            // 设置内容体的文件格式是excel
            res.setContentType("application/vnd.ms-excel");
            workbook.write(os);
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
